package com.bupt.liutong.admin.core.base;

import java.io.InputStream;
import java.io.File;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.upload.FormFile;
import org.directwebremoting.WebContextFactory;

import com.bupt.liutong.util.FileUtils;
import com.bupt.liutong.util.StringUtils;
import com.bupt.liutong.util.ImageUtils;

public class FileUploader {
	
	private static String baseUrl;
	private static String basePath;
	
	public String getUrl(HttpServletRequest request) {
		if (StringUtils.isEmpty(baseUrl))
			baseUrl = "/upload";
		return baseUrl;
	}
	
	public String getPath(HttpServletRequest request) {
		if (StringUtils.isEmpty(basePath))
			basePath = request.getSession().getServletContext().getRealPath("/upload");
		return basePath;
	}
	
	/**
	 * AJAX上传图片
	 * @param is
	 * @param clientPath
	 * @return
	 */
	public String uploadImage(InputStream is, String clientPath) {
		String[] tempStrArr = clientPath.split(FileUtils.FILE_SEPARATOR_REGEX);
		String fileName = tempStrArr[tempStrArr.length - 1];
		// 文件名中文转拼音
		if(StringUtils.containsChinese(fileName))
			fileName = StringUtils.toPinyin(fileName);
		// 时间戳
		long timeStamp = new Date().getTime();
		fileName = timeStamp + "_" + fileName;
		HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
		String uploadUrl = getUrl(request) + "/image/temp/" + fileName;
		String uploadPath = getPath(request) + File.separator + "image"
				+ File.separator + "temp" + File.separator + fileName;
		FileUtils.forceCopyFile(is, uploadPath);
		return uploadUrl;
	}

	/**
	 * 上传图片并在数据库中保存
	 * @param photo
	 * @param photoDao
	 * @param request
	 */
	public void uploadImage(Photo photo, PhotoDao photoDao,
			HttpServletRequest request) {
		try {
			FormFile file = photo.getFile();
			if (file != null && file.getFileSize() > 0) {
				String fileName = file.getFileName();
				photo.setDes(FileUtils.getFileName(fileName));
				// 时间戳
				long timeStamp = new Date().getTime();
				// 文件名中文转拼音
				if (StringUtils.containsChinese(fileName))
					fileName = StringUtils.toPinyin(fileName);
				fileName = timeStamp + "_" + fileName;
				// 写入DB，并保存文件
				photo.setUrl(getUrl(request) + photo.getUrlPrefix() + fileName);
				photo.setFilePath(photo.getPathPrefix() + fileName);
				photo.setThumbUrl(getUrl(request) + photo.getUrlPrefix()
						+ "thumb/" + fileName);
				photo.setThumbPath(photo.getPathPrefix() + "thumb"
						+ File.separator + fileName);
				photoDao.insertPhoto(photo);
				FileUtils.forceCopyFile(file.getInputStream(), getPath(request)
						+ photo.getFilePath());
				ImageUtils.scaleByWidth(getPath(request) + photo.getFilePath(),
						getPath(request) + photo.getThumbPath(), 300);
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO Delete photo files
			throw new RuntimeException();
		}
	}
	
	public void uploadImages(PhotosForm photosForm, PhotoDao photoDao,
			HttpServletRequest request) {
		for (int i = 0; i < photosForm.getNewPhotoDeses().length; i++) {
			Photo photo = photosForm.getNewPhoto(i);
			this.uploadImage(photo, photoDao, request);
		}
	}
	
	public void deleteImage(Integer id, PhotoDao photoDao, HttpServletRequest request){
		Photo photo = photoDao.deletePhoto(id);
		FileUtils.deleteFile(getPath(request) + photo.getFilePath());
	}
	
	public void updateImages(PhotosForm photosForm, PhotoDao photoDao, HttpServletRequest request){
		//delete some photos
		String deletePhotoIds = request.getParameter("deletePhotoIds");
		if (!StringUtils.isEmpty(deletePhotoIds)) {
			String[] photoIds = deletePhotoIds.split(",");
			for(String photoId:photoIds)
				deleteImage(Integer.valueOf(photoId), photoDao, request);
		}
		
		//update some photo info
		for (int i = 0; i < photosForm.getPhotoDeses().length; i++) {
			Photo photo = photosForm.getPhoto(i);
			if (photo.getId() != null)
				photoDao.updatePhoto(photo);
		}
	}
}
